//
//  VCImagePickerTool.m
//  VideoCollage
//
//  Created by Mac on 2018/7/20.
//  Copyright © 2018年 stoneobs.qq.com. All rights reserved.
//

#import "VCImagePickerTool.h"
#import "XFPhotoLibraryManager.h"
#import <Photos/Photos.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AssetsLibrary/AssetsLibrary.h>
@interface VCImagePickerTool()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property(nonatomic, strong) UIImagePickerController                     *pickerVC;/**< <##> */
@end
@implementation VCImagePickerTool
- (instancetype)initWithFormViewController:(UIViewController *)formViewController{
    if (self == [super init]) {
        _formViewController = formViewController;
    }
    return self;
}
- (UIImagePickerController *)pickerVC{
    if (!_pickerVC) {
        _pickerVC = [[UIImagePickerController alloc] init];
        _pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;    //设置来源为摄像头
        _pickerVC.delegate = self;
    }
    return _pickerVC;
}
- (void)show{
    UIAlertController * sheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    

    
    UIAlertAction * camer = [UIAlertAction actionWithTitle:@"拍照"
                                                     style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * _Nonnull action) {
                                                       if (!TARGET_OS_SIMULATOR) {
                                                           self.pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
                                                           [self.formViewController presentViewController:self.pickerVC animated:YES completion:nil];
                                                       }
                                                       
                                                   }];
    [sheet addAction:camer];
    UIAlertAction * photo =[UIAlertAction actionWithTitle:@"拍摄"
                                                    style:UIAlertActionStyleDefault
                                                  handler:^(UIAlertAction * _Nonnull action) {
                                                      
                                                      self.pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
                                                      self.pickerVC.mediaTypes = @[(NSString *)kUTTypeMovie];
                                                      self.pickerVC.allowsEditing = NO;
                                                      self.pickerVC.videoMaximumDuration = 20;
                                                      [self.formViewController presentViewController:self.pickerVC animated:YES completion:nil];
                                                  }];
    [sheet addAction:photo];
    UIAlertAction * cancle = [UIAlertAction actionWithTitle:@"取消"
                                                      style:UIAlertActionStyleDefault
                                                    handler:^(UIAlertAction * _Nonnull action) {
                                                        
                                                    }];
    [sheet addAction:cancle];
    
    UIPopoverPresentationController *popPresenter = [sheet
                                                     popoverPresentationController];
    VCItemEditViewController * vc = (id)self.formViewController;
    popPresenter.sourceView = vc.popView;

    [self.formViewController presentViewController:sheet animated:YES completion:nil];
}
#pragma mark --UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    [SVProgressHUD showWithStatus:@"Saving to the system photo album, please wait"];
    if ([type isEqualToString:(NSString *)kUTTypeImage]) {
        //图片保存和展示
        UIImage *image;
        if (picker.allowsEditing) {
            image = [info objectForKey:UIImagePickerControllerEditedImage]; //允许编辑，获取编辑过的图片
        }
        else{
            image = [info objectForKey:UIImagePickerControllerOriginalImage]; //不允许编辑，获取原图片
        }
        [XFPhotoLibraryManager savePhotoWithImage:image andAssetCollectionName:nil withCompletion:^(UIImage *image, NSError *error, NSString *assetID) {
            
            if (!error) {
                if (self.takePhotosCompletionBlock) {
                    self.takePhotosCompletionBlock(image, error, assetID);
                }
            }else{
                DDLogInfo(@"保存图片错误:%@",error);
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                [picker dismissViewControllerAnimated:YES completion:nil];
            });

        }];
        //UIImageWriteToSavedPhotosAlbum(image,self,@selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
    else if([type isEqualToString:(NSString *)kUTTypeMovie]){
        //视频保存后 播放视频
        NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL];
        NSString *urlPath = [url path];
        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlPath)) {
            
            [XFPhotoLibraryManager saveVideoWithVideoUrl:[NSURL fileURLWithPath:urlPath] andAssetCollectionName:nil withCompletion:^(NSURL *vedioUrl, NSError *error, NSString *assetID) {
                
                if (!error) {
                    if (self.shootCompletionBlock) {
                        AVAsset * asset = [AVAsset assetWithURL:vedioUrl];
//                        UIImage *image = [self thumbnailImageRequestWithVideoUrl:videoUrl andTime:0.01f];
                        self.shootCompletionBlock(vedioUrl, CMTimeGetSeconds(asset.duration), nil, error, assetID);
                    }
                }else{
                    DDLogInfo(@"保存视频错误:%@",error);
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                    [picker dismissViewControllerAnimated:YES completion:nil];
                });
                
            }];
            
           // UISaveVideoAtPathToSavedPhotosAlbum(urlPath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        }
    }
    
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        NSLog(@"保存图片过程中发生错误，错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"视频保存成功.");
        
    }
}
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        NSLog(@"保存视频过程中发生错误，错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"视频保存成功.");

    }
}
@end
